﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SPMS.Common
{
    /// <summary>
    /// 常规功能要求定义。
    /// </summary>
    public class GenericFunctionalityRequirement : IPermissionRequirement
    {
        #region ---Constructor

        /// <summary>
        /// 初始化类型<see cref="GenericFunctionalityRequirement" />的新实例。
        /// </summary>
        /// <param name="functionalities">要求的功能编号。</param>
        public GenericFunctionalityRequirement(params int[] functionalities)
        {
            //保存设置
            this.m_Functionalities = functionalities ?? new int[0];
        }

        #endregion

        #region ---IPermissionRequirement

        /// <summary>
        /// 判断当前登录用户是否满足功能权限要求。
        /// </summary>
        /// <param name="principal">窗体认证用户信息。</param>
        /// <returns>
        /// 如果满足，则返回<c>true</c>，否则返回<c>false</c>。
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public bool IsValid(FormsPrincipal principal)
        {
            //判断是否指定了要求的功能编号
            if (this.m_Functionalities.Length == 0)
            {
                //如果没有指定，则总是满足
                return true;
            }

            //循环判断是否包含功能
            foreach (int functionality in this.m_Functionalities)
            {
                //判断是否包含
                if (Array.IndexOf<int>(principal.Functionalities, functionality) == -1)
                {
                    //返回不满足
                    return false;
                }
            }

            //默认返回满足
            return true;
        }

        #endregion

        #region ---Field

        /// <summary>
        /// 要求的功能编号集合。
        /// </summary>
        private int[] m_Functionalities;

        #endregion
    }
}
